package com.sojson.util.file.format.interfaces.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.sojson.util.StringUtil;
import com.sojson.util.file.format.interfaces.FileFormatInterface;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import lombok.extern.slf4j.Slf4j;

/**
 * Spire文件转换工具类
 *
 * @author liu
 * @date 2022-09-05
 */
@Slf4j
public class SpireUtilImpl implements FileFormatInterface {

    private static SpireUtilImpl instances;

    /**
     * word转pdf
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    @Override
    public ByteArrayOutputStream wordToPdf(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();

            Document doc = new Document();
            doc.loadFromStream(inputStream, FileFormat.Docx);
            doc.saveToFile(outputStream, FileFormat.PDF);
            return outputStream;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * word转pdf
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    @Override
    public byte[] wordToPdfByte(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = wordToPdf(inputStream);
            return outputStream.toByteArray();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    public static SpireUtilImpl getInstances() {
        if (StringUtil.isBlankObject(instances)) {
            instances = new SpireUtilImpl();
        }
        return instances;
    }

}